package bbs.controller;

import bbs.annotation.VerifyParam;
import bbs.controller.base.ABaseController;
import bbs.entity.config.AdminConfig;
import bbs.entity.dto.*;
import bbs.entity.vo.ResponseVO;
import bbs.exception.BusinessException;
import bbs.service.SysSettingService;
import bbs.utils.JsonUtils;
import bbs.utils.OKHttpUtils;
import bbs.utils.StringTools;
import com.alibaba.fastjson.JSON;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
@RequestMapping("/setting")
public class SysSettingController extends ABaseController {

    @Resource
    private SysSettingService sysSettingService;

    @Resource
    private AdminConfig adminConfig;

    @RequestMapping("/getSetting")
    public ResponseVO getSysSetting() {
        return getSuccessResponseVO(sysSettingService.refresCache());
    }

    @RequestMapping("/saveSetting")
    public ResponseVO saveSetting(
            @VerifyParam(required = true) SysSetting4AuditDto auditDto,
            @VerifyParam(required = true) SysSetting4PostDto postDto,
            @VerifyParam(required = true) SysSetting4CommentDto commentDto,
            @VerifyParam(required = true) SysSetting4LikeDto likeDto,
            @VerifyParam(required = true) SysSetting4RegisterDto registerDto,
            @VerifyParam(required = true) SysSetting4EmailDto emailDto
            )
    {
        SysSettingDto settingDto = new SysSettingDto();
        settingDto.setAuditSetting(auditDto);
        settingDto.setPostSetting(postDto);
        settingDto.setCommentSetting(commentDto);
        settingDto.setLikeSetting(likeDto);
        settingDto.setRegisterSetting(registerDto);
        settingDto.setEmailSetting(emailDto);

        sendWebRequest();
        sysSettingService.saveSetting(settingDto);

        return getSuccessResponseVO(null);
    }

    private void sendWebRequest() {
        String appKey = adminConfig.getInnerApiAppKey();
        String appSecret = adminConfig.getInnerApiAppSecret();
        Long timeStamp = System.currentTimeMillis();
        String sign = StringTools.encodeMd5(appKey + timeStamp + appSecret);
        String url = adminConfig.getWebApiUrl() + "?appKey=" + appKey + "&timeStamp=" + timeStamp + "&sign=" + sign;
        String responseJson = OKHttpUtils.getRequest(url);
        ResponseVO responseVO = JsonUtils.convertJson2Obj(responseJson, ResponseVO.class);
        if (!STATUC_SUCCESS.equals(responseVO.getStatus())) {
            throw new BusinessException("缓存刷新失败");
        }
    }
}
